<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>微信单点登录</title>
    <script type="text/javascript"
            src="//assets.zjzwfw.gov.cn/assets/ZWJSBridge/1.1.0/zwjsbridge.js"></script>
</head>

<body>
用户信息：<br>
<pre id="user-result"></pre>

<button id="openLink">跳转第三方应用</button>
<script>
    window.onload = function load() {
        console.log('load');
        // 微信小程序环境判断
        if (window.navigator.userAgent.toLowerCase().includes('miniprogram/wx') || window.__wxjs_environment === 'miniprogram') {
            const searchParams = new URLSearchParams(window.location.search);
            const ticketId = searchParams.get("ticketId"); // 从url参数获取ticketId
            if (ticketId) {
                fetch(`/auth/login?ticketId=${ticketId}`, { // 调用自有登录接口，后端将登录态写到cookie
                    method: 'post'
                }).then(response => {
                    return response.text();
                }).then(result => {
                    console.log('result==', result);
                    // 获取用户信息，需要登录态
                    fetch(`/auth/userInfo`, {
                        method: 'post'
                    }).then(response => {
                        return response.json();
                    }).then(result => {
                        console.log('user info==', result);
                        document.getElementById("user-result").innerText = JSON.stringify(result, null, 2)
                    })
                })
            } else {
                console.log('url has not ticketId');
                // TO DO
            }
            // 其他环境
        } else {
            //TODO
        }

        // 跳转第三方应用
        document.querySelector('#openLink').addEventListener('click', function () {
            ZWJSBridge.openLink({
                url: "https://mapi.zjzwfw.gov.cn/web/mgop/gov-open/zj/2001972461/reserved/index.html",
            })
                .then((result) => {
                    console.log("result", result);
                })
                .catch((error) => {
                    console.log("error", error);
                });
        })
    }
</script>
</body>

</html>
